package xyz.zhzby.cyzx.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.ucenter.dto.response.Info;
import xyz.zhzby.cyzx.ucenter.dto.response.InterestResponse;
import xyz.zhzby.cyzx.ucenter.entity.Interest;
import xyz.zhzby.cyzx.ucenter.mapper.InterestMapper;
import xyz.zhzby.cyzx.ucenter.service.IInterestService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 兴趣表 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-16
 */
@Service
public class InterestServiceImpl extends ServiceImpl<InterestMapper, Interest> implements IInterestService {

    @Override
    public List<Info> getInterestsByUserId(Long id) {
        return baseMapper.getInterestsByUserId(id);
    }

    @Override
    public RestResponse<List<InterestResponse>> getAllInterests() {
        LambdaQueryWrapper<Interest> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Interest::getId);
        List<Interest> interests = baseMapper.selectList(qw);
        List<InterestResponse> list = build(interests);
        return RestResponse.success(list);
    }

    @ApiOperation("使用递归方法建兴趣列表")
    private static List<InterestResponse> build(List<Interest> treeNodes) {
        List<InterestResponse> trees = new ArrayList<>();
        for (Interest treeNode : treeNodes) {
            if (treeNode.getParentId().equals(0L)) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    @ApiOperation("递归查找子节点")
    private static InterestResponse findChildren(Interest treeNode, List<Interest> treeNodes) {
        InterestResponse res = new InterestResponse();
        res.setValue(treeNode.getId());
        res.setLabel(treeNode.getName());
        res.setChildren(new ArrayList<>());

        for (Interest node : treeNodes) {
            if (treeNode.getId().equals(node.getParentId())) {
                res.getChildren().add(findChildren(node, treeNodes));
            }
        }
        if (res.getChildren().isEmpty()) {
            res.setChildren(null);
        }
        return res;
    }


}
